package com.yasee.chronic.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yasee.chronic.R;
import com.yasee.chronic.manager.DataManager;
import com.yasee.chronic.model.LoginBean;
import com.yasee.chronic.model.User;
import com.yasee.chronic.util.CommonUtils;
import com.yasee.chronic.util.HttpRequest;
import com.yasee.chronic.util.MyUtils;
import com.yasee.chronic.widget.MyDialog;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.manager.HttpManager;
import zuo.biao.library.util.CommonUtil;
import zuo.biao.library.util.Log;
import zuo.biao.library.util.SettingUtil;

public class LoginActivity extends BaseActivity implements View.OnClickListener, View.OnLongClickListener, OnHttpResponseListener {

    private static final String TAG = "LoginActivity";

    private TextView btnLogin;
    private AutoCompleteTextView atAccount;
    private EditText etPass;
    private CheckBox cbRemember;
    private ImageView ivSettings;
    private ImageView ivUsers;

    private List<User> users;
    private ArrayAdapter<User> adapter;
    //启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 启动这个Activity的Intent
     *
     * @param context
     * @return
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, SettingActivity.class);
    }

    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

    }

    @Override
    public void initView() {
        btnLogin = findViewById(R.id.btn_login);
        atAccount = findViewById(R.id.at_account);
        etPass = findViewById(R.id.et_pass);
        cbRemember = findViewById(R.id.cb_remember);
        ivSettings = findView(R.id.iv_settings);
        ivUsers = findView(R.id.iv_users);
        cbRemember.setChecked(true);
        users = DataManager.getInstance().getUsers();
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, users);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    @Override
    public void initData() {//必须调用
//        CommonUtils.setSystemTime(System.currentTimeMillis(), context);
        Log.e(TAG,"当前时间："+ System.currentTimeMillis());
        Log.e(TAG,"当前时间："+ (System.currentTimeMillis() + 1000 * 60 * 60 * 24));
        CommonUtils.setSystemTime((System.currentTimeMillis() + 1000 * 60 * 60 * 24), context);
        if(users.size()> 0){
            atAccount.setText(users.get(0).getAccount());
            etPass.setText(users.get(0).getPass());
        }
    }

    private void getLoginAsync() {
        if(atAccount.getText().toString().trim().isEmpty()){
            showShortToast("请输入账号");
            return;
        }
        if(etPass.getText().toString().trim().isEmpty()){
            showShortToast("请输入密码");
            return;
        }
        if(HttpRequest.URL_BASE.isEmpty()){
            showShortToast("请输入服务器地址");
            return;
        }
        HttpRequest.login(atAccount.getText().toString().trim(), etPass.getText().toString().trim(), 0, this);
    }

    @Override
    public void onHttpResponse(int requestCode, String resultJson, Exception e) {
        switch (requestCode){
            case 0:
                if(resultJson==null){
                    showShortToast("请求失败");
                    return;
                }
                LoginBean loginBean = new Gson().fromJson(resultJson, LoginBean.class);
                Log.e(TAG,"result" + new Gson().toJson(loginBean));
                CommonUtil.token = "Bearer " + loginBean.getAccess_token();
                MyUtils.userID = loginBean.getUser_id() + "";
                if(cbRemember.isChecked()){
                    User user = new User();
                    user.setAccount(atAccount.getText().toString().trim());
                    user.setId(loginBean.getUser_id());
                    user.setPass(etPass.getText().toString().trim());
                    DataManager.getInstance().addUser(user);
                }
                startActivity(MainTabActivity.createIntent(this));
                finish(); // 结束当前的登录 Activity
                break;
            default:
                break;
        }
    }

    private void showUserListDialog() {
        // 创建用户列表对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Select User");
        // 创建ListView
        ListView listView = new ListView(this);
        // 使用传统循环转换
        List<String> usernames = new ArrayList<>();
        for (User user : users) {
            usernames.add(user.getAccount());
        }

        Log.e(TAG,"users++++++++" + usernames.size());

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, usernames);
        listView.setAdapter(adapter);

        AlertDialog dialog = builder.create();

        MyDialog dialog1 = new MyDialog(this, MyDialog.DialogType.NORMAL);

        // 设置ListView的点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String selectedUser = (String) parent.getItemAtPosition(position);
                // 处理用户选择事件，例如填充登录表单
                fillLoginForm(users.get(position));
                // 关闭对话框
                dialog1.dismiss();
            }
        });
        dialog1.setCustomView(listView);
        dialog1.show();
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void initEvent() {//必须调用
        btnLogin.setOnClickListener(this);
        cbRemember.setOnClickListener(this);
        ivSettings.setOnClickListener(this);
        ivUsers.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                Log.i(TAG, "onClick->btnLogin");
                getLoginAsync();
                break;
            case R.id.iv_settings:
                showSystemConfig();
                Log.i(TAG, "onClick->ivSettings");
                break;
            case R.id.cb_remember:
                Log.i(TAG, "onClick->cbRemember");
                break;
            case R.id.iv_users:
//                spinnerUsers.setVisibility(View.VISIBLE);
                showUserListDialog();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onLongClick(View v) {
        return false;
    }

    //生命周期、onActivityResult<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    //生命周期、onActivityResult>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    private void showSystemConfig(){
        MyDialog dialog = new  MyDialog(context, MyDialog.DialogType.EDIT);
        dialog.setTitle("设置服务器地址");
        dialog.setLeftButton("取消", new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setRightButton("确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String add = dialog.getAdd();
                Log.i(TAG, "add = " + add);
                // 将输入的服务器地址保存到SharedPreferences中
                DataManager.getInstance().saveServerAddress(add);
                HttpRequest.URL_BASE = add;
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void fillLoginForm(User user) {
        // 填充登录表单的逻辑
        if (user != null) {
            atAccount.setText(user.getAccount());
            etPass.setText(user.getPass());
        }
    }


    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //内部类,尽量少用<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    //内部类,尽量少用>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

}
